<?php
declare (strict_types = 1);

namespace command\route;

use command\lib\DocParse;
use ReflectionClass;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class RouteCreate extends Command
{

    protected function configure()
    {
        // 指令配置
        $this->setName('ykroute:create')
            ->addArgument('module', Argument::OPTIONAL, "app module name")
            ->setDescription('auto update model');        
    }

    protected function execute(Input $input, Output $output)
    {
        $module = $input->getArgument('module');
        $modulePath = $module?$module."/":'';

        $path = $this->app->getBasePath().$modulePath."controller";

        if (!is_dir($path)) {
            $output->writeln('path is not exist');
            return;
        }
        
        $list = scandir($path);//扫描文件夹，获取文件列表

        $namespace = 'app\controller';

        if($module)$namespace = 'app\\'.$module.'\controller';

        $routeStr = '';

        $controller = config('ykcommand.auto.'.($module?$module.'.controller':'controller'));//如果指定控制器自动生成

        foreach ($list as $key => $value) {
            
            if(is_file($path.'/'.$value)){
                $arr = explode(".",$value);
                if(!empty($controller)&&!in_array($arr[0],$controller))continue;
                
                $class = new ReflectionClass($namespace.'\\'.$arr[0]);//反射类，获取类的对象

                $methods = $class->getMethods();//获取类方法列表
                $tempStr = '';
                foreach ($methods as $method) {
                    if($class->getName()!=$method->getDeclaringClass()->getName())continue;//如果是继承的方法跳过
                    $doc = $method->getDocComment();//获取方法注释
                    $methodDoc = new DocParse($doc,$class->getShortName().'/'.$method->getName());//解析方法注释
                    $tempStr .=$methodDoc->getRoute();//获得解析后的路由字符串
                }

                if($tempStr){
                    $classDoc = new DocParse($class->getDocComment()??'');//获取并解析类注释
                    $routeStr .= "/**".($classDoc->getComment()?:$class->getShortName())."*/".PHP_EOL.$tempStr.PHP_EOL;//拼接路由字符串
                }
                
            }

        }

        $stub = file_get_contents(__DIR__ .  DIRECTORY_SEPARATOR . 'route.stub');//获取路由文件模板

        $pathName = $this->app->getBasePath().$modulePath.'route/route.php';//获取写入路由文件路径和名称

        file_put_contents($pathName,str_replace(['{$route}'],[$routeStr],$stub));//写入路由文件
    	// 指令输出
    	$output->writeln('route');
    }

    
}
